<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +--------------------------------------------------------------
 * | Copyright (c) 2016-2018 http://qxwoo.cn All rights reserved.
 * +--------------------------------------------------------------
 * | y139w [y139w@163.com]
 * +--------------------------------------------------------------
 * | 模型类文件
 * +--------------------------------------------------------------
 */

namespace luo;

use luo\db\Query;
use luo\db\Sql;
use luo\ioc\Ioc;

class Model
{

    /**
     * Query对象
     * @var null|Query
     */
    private $query = null;

    /**
     * 表名
     * @var string
     */
    protected $table = '';

    /**
     * 自动成功
     * @var array
     */
    protected $autoDone = null;

    /**
     * 日期时间格式
     * @var string
     */
    protected $timeFormat = 'Y-m-d H:i:s';

    /**
     * 软删除字段
     * @var string
     */
    protected $softDel = null;

    /**
     * Model constructor.
     * @param string $table
     * @throws \ReflectionException
     */
    public function __construct($table = '')
    {

        // Db类实例化
        $db = Ioc::instance(Db::class);
        // Sql类实例化
        $sql = Ioc::instance(Sql::class);
        // Query类实例化
        $this->query = new Query($db, $sql);
        // 设置表名
        if(empty(trim($table))){
            if(empty($this->table)) {
                // 获取当前对象的类名
                $class = get_class($this);
                if($class != __CLASS__){
                    // 是否含有命名空间
                    if (strpos($class, '\\')) {
                        $classArray = explode('\\', $class);
                        // 获取没有命名空间的类名
                        $table = $classArray[count($classArray) - 1];
                    } else {
                        $table = $class;
                    }
                    // 统一转换为小写
                    $this->table = strtolower($table);
                }
            }
        }else{
            $this->table = strtolower($table);
        }
        // 表名属性是否为空
        if(!empty($this->table)){
            // 不为空时就设置表名
            $this->query->table($this->table);
        }

    }

    /**
     * 设置表名
     * @param $name
     * @return $this
     */
    public function name($name){

        $this->table = $name;
        $this->query->table($name);
        return $this;

    }

    /**
     * 设置表名
     * @param $name
     * @return Model
     */
    public function table($name){
        return $this->name($name);
    }

    /**
     * 添加记录
     * @param array $data
     * @return mixed
     */
    public function insert(array $data){

        // 自动完成字段的添加
        if(!is_null($this->autoDone)){
            $auto_time = [];
            // 如果是字符串就把字符串处理为数组
            if(is_string($this->autoDone)){
                $auto_time = [$this->autoDone];
            }
            // 如果是数组就直接赋值
            if(is_array($this->autoDone)){
                $auto_time = $this->autoDone;
            }
            // 循环处理自动完成字段
            foreach($auto_time as $key=>$val){
                if(is_numeric((int)$key)){
                    $key = $val;
                    $val = $this->timeFormat;
                }
                $data[$key] = date($val);
            }
        }
        return $this->query->insert($data);

    }

    /**
     * 删除记录
     * @param null $pk
     * @return mixed
     */
    public function delete($pk = null){
        return $this->query->delete($pk);
    }

    /**
     * 更新记录
     * @param array $data
     * @param null $pk
     * @return mixed
     */
    public function update(array $data, $pk = null){

        return $this->query->update($data, $pk);

    }

    /**
     * 记录条数
     * @return mixed
     */
    public function count(){

        return $this->query->count();

    }

    /**
     * 查询所有
     * @return mixed
     */
    public function select(){
        return $this->query->select();
    }

    public function pagination($current, $num = 10){

        // 当前页
        $current = $current ? $current : 1;
        // 每一页条数
        $pageNumber = $num;
        // 总记录数
        $count = $this->count();
        // 总页数
        $total = ceil($count / $pageNumber);
        // 分页开始位置
        $offset = ($current - 1) * $pageNumber;
        // 分页
        $this->limit([$offset, $pageNumber]);
        // 获取当前页记录
        $records = $this->select();
        // 中间几页处理
        $page = new Page($current, $total);
        // 获取分页数据
        $pager = $page->show();
        $pager['count'] = $count;
        $pager['number'] = $num;
        // 组装数据
        $data = ['data' => $records, 'pager'=> $pager];
        return $data;

    }

    /**
     * 开启事务
     * @return mixed
     */
    public function begin(){

        return  $this->query->begin();

    }

    /**
     * 事务回滚
     * @return mixed
     */
    public function rollback(){

        return  $this->query->rollback();

    }

    /**
     * 提交事务
     * @return mixed
     */
    public function commit(){

        return  $this->query->commit();

    }

    /**
     * 查询单条
     * @param null $pk
     * @return mixed
     */
    public function find($pk = null){
        return $this->query->find($pk);
    }

    /**
     * Join连接
     * @param $table
     * @param null $condition
     * @param string $type
     * @return object $this
     */
    public function join($table, $condition = null, $type = 'inner'){
        //$this->query = $this->query->join($table, $condition, $type);
        $this->query->join($table, $condition, $type);
        return $this;
    }

    /**
     * WHERE条件语句
     * @param $field
     * @param null $operation
     * @param null $condition
     * @param string $type
     * @return object $this
     */
    public function where($field, $operation = null, $condition = null, $type = 'and'){
        $this->query->where($field, $operation, $condition, $type);
        return $this;
    }

    /**
     * WHERE条件语句（或者）
     * @param $field
     * @param null $operation
     * @param null $condition
     * @return object
     */
    public function whereOr($field, $operation = null, $condition = null){
        $this->where($field, $operation, $condition, 'or');
        return $this;
    }

    /**
     * 设置字段
     * @param string $field
     * @return object $this
     */
    public function field($field = ''){
        $this->query->field($field);
        return $this;
    }

    /**
     * 排序查询
     * @param string $order
     * @return $this
     */
    public function order($order = ''){
        $this->query->order($order);
        return $this;
    }

    /**
     * 分页查询
     * @param array $limit
     * @return $this
     */
    public function limit($limit = []){
        $this->query->limit($limit);
        return $this;
    }

    /**
     * 分组查询
     * @param $group
     * @return $this
     */
    public function group($group){
        $this->query->group($group);
        return $this;
    }

    /**
     * GROUP分组查询的条件
     * @param $having
     * @return $this
     */
    public function having($having){
        $this->query->having($having);
        return $this;
    }

    /**
     * 获取最后一次执行的SQL语句
     * @return string
     */
    public function getLastSql(){
        return $this->query->getLastSql();
    }

    /**
     * 魔术方法调用Query对象中的方法
     * @param $name
     * @param $arguments
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        if(method_exists($this->query, $name)){
            return call_user_func_array([$this->query, $name], $arguments);
        }

    }
}